<template>
  <div class="container">
    <div class="app-container" style="padding: 20px">
      <!-- 角色管理 -->
      <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
      <!-- :data 数据源 -->
      <el-table :data="tableData" border style="margin: 20px 0;" size="mini">
        <el-table-column type="index" label="序号" width="100" align="center" />

        <el-table-column prop="name" label="角色" width="100">
          <template #default="{row}">
            <span v-if="!row.isEdit">{{ row.name }}</span>
            <!-- 绑定临时数据 临时数据随便你折腾  我有备份 真正的数据在row.name -->
            <el-input v-else v-model="row.temp.name" size="mini" />
          </template>
        </el-table-column>

        <!-- state是1 显示 启用 否则未启用 -->
        <!-- <el-table-column prop="state" label="是否启用" width="100" /> -->
        <el-table-column label="是否启用" width="100">
          <template #default="{row}">
            <span v-if="!row.isEdit">{{ row.state === 1 ? '启用' : '未启用' }}</span>
            <el-switch v-else v-model="row.temp.state" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述">
          <template #default="{row}">
            <span v-if="!row.isEdit">{{ row.description }}</span>
            <el-input v-else v-model="row.temp.description" type="textarea" size="mini" />
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <!-- 通过默认插槽指定结构 -->
          <!--  -->
          <!-- 文字按钮 -->
          <template #default="{row}">
            <!-- {{ row }} -->
            <!-- obj是这个组件的作者在封装el-table-column组件时，传递给默认插槽的参数 -->
            <div v-if="!row.isEdit">
              <el-button type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button type="text" @click="row.isEdit=true">编辑</el-button>
              <!-- 希望删除时 先弹气泡确认 -->
              <el-popconfirm title="是否删除该角色？" @onConfirm="del(row.id)">
                <template #reference>
                  <!-- 固定显示的结构 -->
                  <el-button type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-else>
              <el-button size="mini" type="primary" @click="edit(row)">确定</el-button>
              <el-button size="mini" @click="cancelEdit(row)">取消</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!--
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      -->
      <el-pagination
        small
        :current-page="page"
        :page-sizes="[3,4,5,6]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />

      <!-- 新增角色对话框 -->
      <el-dialog title="新增角色" :visible.sync="showDialog" width="500px" @close="clear">
        <template #title>新增</template>

        <el-form ref="xx" :model="formObj" :rules="rules" label-width="100px" size="mini">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="formObj.name" />
          </el-form-item>
          <el-form-item label="启用">
            <!-- <el-input></el-input> -->
            <el-switch
              v-model="formObj.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="formObj.description" type="textarea" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button size="mini" type="primary" @click="add">确定</el-button>
          <el-button size="mini" @click="clear">取消</el-button>
        </template>

      </el-dialog>
      <!-- 放置权限弹层 -->
      <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
        <!-- 放置权限数据 -->
        <el-tree
          ref="hhh"
          node-key="id"
          :check-strictly="true"
          :data="permissionData"
          :props="{ label: 'name' }"
          show-checkbox
          default-expand-all
          :default-checked-keys="permIds"
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
            <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getRoleList, addRole, updateRole, deleteRole, getRoleDetail, assignPerm } from '@/api/role'
import { transListToTreeData } from '@/utils'
import { getPermissionList } from '@/api/permission'
export default {
  name: 'Role',
  data() {
    return {
      permIds: [],
      showPermissionDialog: false,
      permissionData: [],
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 4,
      showDialog: false,
      // 表单数据
      formObj: {
        name: '',
        state: 1,
        description: ''
      },
      rules: {
        name: [
          // 必填校验
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          // 必填校验
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 点击确定时触发
    async  btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.hhh.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    },
    async  btnPermission(id) {
      this.currentId = id
      const res = await getPermissionList()
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionData = transListToTreeData(res, 0)
      this.showPermissionDialog = true
    },
    async del(id) {
      await deleteRole(id)// 请求后端
      this.$message.success('删除成功')// 提示
      // 页码回到上一页(条件： 这一页只有一条数据的时候  页码>1)
      if (this.tableData.length === 1 && this.page > 1) this.page--// bug 面试可用
      this.getList()// 重新渲染
    },
    async edit(row) {
      // console.log(row)
      await updateRole({ ...row.temp, id: row.id })
      // 提示
      this.$message.success('修改成功')
      // 重新渲染
      this.getList()
    },
    cancelEdit(row) {
      row.temp.name = row.name
      row.temp.state = row.state
      row.temp.description = row.description
      row.isEdit = false
    },
    add() {
      this.$refs.xx.validate(async isOK => {
        if (isOK) {
          // ...
          await addRole(this.formObj)
          this.$message.success('添加成功')
          this.clear()
          this.getList()
        }
      })
    },
    clear() {
      this.showDialog = false
      this.$refs.xx.resetFields()
      this.formObj = {
        name: '',
        state: 1,
        description: ''
      }
    },
    handleSizeChange(val) {
      // console.log(val)
      // 更新每页数据条数
      this.pageSize = val
      // 重置页码（防止上一次每页条数过小 导致页码太大）
      this.page = 1
      // 重新获取数据
      this.getList()
    },
    handleCurrentChange(val) {
      // val 就是 当前点击页码
      // console.log(val)
      // 更新页码
      this.page = val
      // 重新获取数据
      this.getList()
    },
    async getList() {
      const { rows, total } = await getRoleList(this.page, this.pageSize)
      // console.log(res)
      this.tableData = rows
      this.tableData.forEach(item => {
        // item.isEdit = false// 给每一行数据都添加一个标记 用于控制自己的编辑态
        // ‘没用’ => 改了item.isEdit 但是没有重新渲染页面 => 没有响应式效果
        // 这个isEdit是临时加入的 => vue没有做响应式处理  => this.$set(数据, 待添加的字段名, 初始值)
        // this.$set => 给临时加入的字段 提供响应式效果
        this.$set(item, 'isEdit', false)
        this.$set(item, 'temp', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })

      this.total = total
    }
  }
}
</script>
